﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace KTX
{
    public partial class FrmDemo : Form
    {
        private SqlConnection cnn;

        public FrmDemo()
        {
            InitializeComponent();

            Configuration _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var strConnectionString = _config.ConnectionStrings.ConnectionStrings[1].ConnectionString;

            cnn = new SqlConnection(strConnectionString);
        }

        private void cmdLoad_Click(object sender, EventArgs e)
        {
            try
            {
                if (cnn.State == ConnectionState.Closed) cnn.Open();
                //var sql = @"select * from tb_Privilege a join tb_User b on a.Id = b.Role";
                var cmd = new SqlCommand("select * from tb_Privilege", cnn);
                //cmd.CommandText = sql;

                var tb = new DataTable();
                // var result = cmd.ExecuteReader();
                // tb.Load(result);

                dataGridView1.DataSource = tb;

                //var res = new SqlDataAdapter(cmd);
                //var tb = new DataTable();
                //res.Fill(tb);
                //dataGridView1.DataSource = tb;

            }
            catch (Exception hehe)
            {
                MessageBox.Show(hehe.Message);
            }

        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (cnn.State == ConnectionState.Closed) cnn.Open();
                var str = String.Format("insert into tb_Privilege(Id, Name) Values({0},'{1}')", txtID.Text, txtName.Text);

                //var hee = "insert into tb_Privilege(Id, Name) Values (" + 1091 + ", '" + 55 + "')";
                //var okk = String.Format("insert into tb_Privilege(Id, Name) Values(?,'?')");

                var cmd = new SqlCommand(str, cnn);

                /*
                SqlParameter id = new SqlParameter("id", 111);
                SqlParameter ten = new SqlParameter("ten", "Hoài An");

                cmd.Parameters.Add(id);
                cmd.Parameters.Add(ten);*/

                cmd.ExecuteNonQuery();

                cmd = new SqlCommand("select * from tb_Privilege", cnn);
                //cmd.CommandText = sql;

                var tb = new DataTable();
                var result = cmd.ExecuteReader();
                tb.Load(result);

                dataGridView1.DataSource = tb;
            }
            catch (Exception hehe)
            {
                MessageBox.Show(hehe.Message);
            }
        }
    }
}